﻿$(function () {
	localStorage.setItem('videoUrl', '');
	localStorage.setItem('videoOrder', '');
	var client;
	$.ajax({
		url: "/admin/Uploads/uploadCredentials",
		data: {},
		type: "post",
		async: false,
		dataType: "json",
		success: function (data) {
			client = new OSS({
				accessKeyId: data.data.accessKeyId,
				accessKeySecret: data.data.accessKeySecret,
				stsToken: data.data.securityToken,
				bucket: 'vedioqingou',
				region: 'oss-cn-hangzhou'
			})
		}
	});
	var files;
	layui.use(['layer', 'element', 'form', 'upload'], function () {
		let layer = layui.layer,
			element = layui.element,
			form = layui.form,
			upload = layui.upload;
		let uploadInst = upload.render({
			elem: '#upload',
			accept: 'file',
			auto: false,
			multiple: true,
			choose: function (obj) {
				files = obj.pushFile();
				$(".file-list").removeClass("layui-hide");
				$(".all-upload").removeClass("layui-hide");
				obj.preview(function (index, file, result) {
					let tr = $(["<tr id='upload-" + index + "'>",
						"<td>" + file.name + "</td>",
						"<td>" + (file.size / 1024).toFixed(1) + "KB</td>",
						"<td>等待上传</td>",
						"<td>",
						// "<button class='layui-btn layui-mini file-reload layui-hide'>重新上传</button>",
						"<button class='layui-btn layui-mini layui-btn-danger file-del'>删除</button>",
						"</td>",
						"</tr>"
					].join(""));

					tr.find(".file-reload").on("click", function () {
						obj.upload(index, file);
					})

					tr.find(".file-del").on("click", function () {
						delete files[index];
						tr.remove();
					})

					$("table").append(tr);
				});
			},
			
		})
	})

	$('.all-upload').click(function () {
		let arrFiles = Object.values(files);
		let arrFilesIndex = Object.keys(files);
		for (let i in arrFiles) {
			uploadOssPut(arrFiles[i].name, arrFiles[i],arrFilesIndex[i]);
		}
	})

	function uploadOssPut(name, file,fileIndex) {
		var tr = $("table").find('tr#upload-' + fileIndex),tds = $(tr).children();
		tds.eq(2).html("<span style='color:#5FB878;'>上传中</span>")
		client.put(fileName(name),file).then(function (v) {
			if (v.res.status === 200) { //上传成功
				var videoList = localStorage.getItem('videoUrl');
				let obj = {
					name:v.name,
					url:v.url
				}
				localStorage.setItem('videoUrl', videoList + "#" + JSON.stringify(obj));
				tds.eq(2).html("<span style='color:#5FB878;'>上传成功</span>")
				tds.eq(3).html(""); //清空操作
				delete files[fileIndex];
				return false;
			} else {
				tds.eq(2).html("<span style='color:#FF5722;'>上传失败</span>")
				tds.eq(3).find(".file-reload").removeClass("layui-hide"); //清空操作
			}
		})
	}

})